
<!--配送商端 销售管理 手术跟台销售订单列表 响应-->
<template>
  <div class="response-box">
    <el-container class="response-box-cont">
      <!-- 响应时候显示，是否同步推送供应商 -->
      <div
        class="push-supplier-box"
        v-show="false">
        <el-checkbox v-model="pushSupplier.isPushSupplier">同步推送供应商</el-checkbox>
        <el-form
          v-show="pushSupplier.isPushSupplier"
          :model="pushSupplier"
          :rules="pushSupplierRules"
          ref="pushSupplier"
          label-width="100px"
          class="demo-ruleForm">
          <el-form-item
            label="供应商"
            prop="supplierId"
            style="margin:0;">
            <el-select
              v-model="pushSupplier.supplierId"
              placeholder="请选择">
              <el-option
                v-for="item in partnerListData"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <p v-show="pushSupplier.isPushSupplier && pushSupplier.supplierId">是否入住M平台： <span style="color:red;">{{ pushSupplier.isCheckInMplatform ? '是' : '否' }}</span></p>
      </div>
      <h3 class="title">病人信息</h3>
      <RecordInfo
        :record-form="patientInfoColumns"
        :record-data="topInfo"/>
      <file-list
        :file-list-arr="topInfo.fileUrl"
      />
      <h3 class="title">订单信息</h3>
      <RecordInfo
        :record-form="headerPartialCollectionColumns"
        :record-data="topInfo">
        <template v-slot:recordInfoslot="slotProp">
          <div class="solt-info">
            <span class="left-span">
              销售产品总数
              <span class="right-span">{{ computedCountList.saleOrderAllSum }}</span>
            </span>
            <span>
              品种数
              <span>{{ computedCountList.varietiesCount }}</span>
            </span>
            <span>
              总金额:
              <span class="price">{{ getFormatterPrice(computedCountList.detailAmount || 0) }}</span>
            </span>
          </div>
        </template>
      </RecordInfo>
      <div>
        <el-editable
          v-if="Number($route.query.isShowList)===0"
          height="400"
          :data="ordertableData"
          :columns="detailPartialCollectionColumns"
        >
          <template
            slot="default-registrationNumber"
            slot-scope="scope">
            <div>
              <cell-registration
                :key="scope.row.registrationNumber"
                :regis-no="scope.row.registrationNumber"
                :content="'注册证已过期，点击查看详细信息'"
                :status="scope.row.isNoExpire"
                :regis-data="scope.row.registrationInfo"
              />
            </div>
            <!-- <el-button
              :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
              v-html="regisNoButton(scope.row)"
              type="text"
              @click="showPdfRegistion(scope.row.registrationId)"
            /> -->
          </template>
        </el-editable>
      </div>
      <el-footer>
        <el-pagination
          v-if="Number($route.query.isShowList)===0"
          align="right"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="curPage"
          :page-sizes="PAGE_NUMBER"
          :page-size="pageSize"
          :layout="PAGINATION_LAYOUT"
          :total="totalElements"
        />
        <div>
          <el-form
            v-if="Number($route.query.isShowList) !== 0"
            :inline="true">
            <el-form-item>
              <el-button @click="removeProducts()">批量删除</el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="addProduct">添加产品</el-button>
            </el-form-item>
          </el-form>
          <el-editable
            v-if="Number($route.query.isShowList) !== 0"
            height="600"
            :data="ordertableData"
            :columns="responseAddColumns"
            @selection-change="handleSelectionChange"
          >
            <template
              slot="default-price"
              slot-scope="scope">
              <el-input-number
                :disabled="scope.row.isEdit"
                v-model="scope.row.price"
                :min="0"
                :max="9999999"
                class="num-box"
                size="mini"
                :precision="3"
              />
              <el-button
                v-if="scope.row.isEdit"
                type="text"
                @click="scope.row.isEdit = false"
              >编辑</el-button
              >
              <el-button
                v-else
                type="text"
                @click="changePriceSbumit(scope,$event)"
              >确定</el-button
              >
            </template>
            <template
              slot="default-purchaseNum"
              slot-scope="scope">
              <el-input-number
                :disabled="scope.row.isEditNum"
                v-model="scope.row.purchaseNum"
                size="mini"
                :min="1"
                :max="9999999"
              />
              <el-button
                v-if="scope.row.isEditNum"
                type="text"
                @click="scope.row.isEditNum = false"
              >编辑</el-button
              >
              <el-button
                v-else
                type="text"
                @click="changeNumSbumit(scope,$event)"
              >确定</el-button
              >
            </template>
            <template
              slot="default-action"
              slot-scope="{row}">
              <el-button
                type="text"
                @click="removeProducts(row)">删除</el-button>
            </template>
          </el-editable>
        </div>
      </el-footer>
    </el-container>
    <!-- 添加产品 -->
    <el-dialog
      title="添加产品"
      width="1200px"
      :visible="dialogVisibel"
      @close="closeDialog">
      <SearchForms
        show-collapse
        :data="computedProductListSearchForm"
        :compact-data="compactProductListSearchForm"
        @searchForm="searchForm"
        @resetForm="resetForm"
        ref="search"
      />
      <el-editable
        height="400"
        :data="dialogTableData"
        :columns="dialogColumns"
        @selection-change="dialogHandleSelectionChange"
      >
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <el-button
            :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
            v-html="regisNoButton(scope.row)"
            type="text"
            @click="showPdfRegistion(scope.row.registrationId)"
          />
        </template>
      </el-editable>
      <el-footer>
        <el-pagination
          align="right"
          class="pagination"
          @size-change="dialogHandleSizeChange"
          @current-change="dialogHandleCurrentChange"
          :current-page="dialogPageList.curPage"
          :page-sizes="dialogPageList.PAGE_NUMBER"
          :page-size="dialogPageList.pageSize"
          :layout="dialogPageList.PAGINATION_LAYOUT"
          :total="dialogPageList.totalElements"
        />
      </el-footer>

      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button
          type="primary"
          @click="confirmDialog">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  patientInfoColumns,
  headerPartialCollectionColumns,
  detailPartialCollectionColumns,
  responseAddColumns,
  commonProductListSearchForm,
  dialogColumns,
  ORDER_STATUS,
  sexMap
} from './const'
import { mapMutations } from 'vuex'
import {
  hospitalHosCooperationProdList,
  enumSelectorhosDealerUpEnterpriseSelector,
  getAuthItemCommonQuery,
  enumSelectorhosDealerSuperDealer,
  getCertificate,
  authItemDealerCooperationProdList
} from '@const/productCenterApiV2'
import SearchForms from '@components/businesscomponents/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import RecordInfo from '@/moduleComponents/beforeSettle/distributorSide/purchasingManagement/record'
import fileList from '@/moduleComponents/beforeSettle/fileList'
import ElEditable from '@components/el-editable'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import {
  YyPssFollowOrderRefuse,
  YyPssFollowOrderFinish,
  YyPssFollowOrderResponseOrder,
  YyPssFollowOrdergetById,
  YyPssFollowOrderItemPageList,
  YyPssFollowOrderAddOrder,
  YyPssFollowOrderUpdatePrice, // 编辑价格
  YyPssFollowOrderUpdateNumber, // 编辑数量
  YyPssFollowOrderDelProduct, // 删除
  partnerList,
  enterMplatform
} from '@const/beforeSettleApi'
import { getFormatterPrice } from '@const/filter'
import { hasIn } from 'lodash'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
export default {
  data () {
    return {
      options: [],
      patientInfoColumns,
      headerPartialCollectionColumns,
      detailPartialCollectionColumns,
      tableData: [],
      ordertableData: [],
      responseAddColumns,
      dialogVisibel: false,
      curPage: 1,
      PAGE_NUMBER,
      dialogColumns,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      dialogPageList: {
        curPage: 1,
        PAGE_NUMBER,
        PAGINATION_LAYOUT,
        totalElements: 0
      },
      totalElements: 0,
      commonProductListSearchForm,
      searchQuery: {},
      dialogTableData: [],
      dialogTableSelectData: [],
      tableSelectData: [],
      topInfo: {},
      changeCompanyList: [],
      headerForm: {
        supplierId: '',
        isChecked: ''
      },
      computedCountList: {
        saleOrderAllSum: ``, // 销售产品总数
        varietiesCount: ``, // 品种数
        detailAmount: ``// 小计金额
      },

      pushSupplier: {
        isPushSupplier: false,
        supplierId: '',
        isCheckInMplatform: true
      },
      pushSupplierRules: {
        supplierId: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      partnerListData: []
    }
  },
  components: {
    RecordInfo,
    ElEditable,
    SearchForms,
    fileList,
    CellRegistration
  },
  computed: {
    compactProductListSearchForm () {
      return this.computedProductListSearchForm.slice(0, 2)
    },
    // 计算查询条件表单
    computedProductListSearchForm () {
      return this.commonProductListSearchForm
    }
  },
  watch: {
    tableData: {
      immediate: true,
      handler (val) {
        // console.log(this.tableData,'this.tableData')
        // this.computedCountList.varietiesCount = this.tableData.length
        // // this.computedCountList.saleOrderAllSum = 0
        // let detailAmount = 0
        // this.tableData.forEach(item => {
        //   // this.computedCountList.saleOrderAllSum += Number(item.purchaseNum)
        //   // detailAmount += (item.buyPrice === undefined ? 0 : item.buyPrice * Number(item.purchaseNum))
        // })
        // this.computedCountList.detailAmount = detailAmount
      }
    },
    // 判断供应商是否入住M平台
    'pushSupplier.supplierId' (val) {
      if (val) {
        this.isSettleInM()
      }
    }
  },
  mounted () {
    this.initNavButtons()
    this.getDeverInfo()// 获取基本信息
    this.changeupCompany()
    this.getDetailList()// 获取产品数据

    this.getPartnerList()
  },
  methods: {
    getFormatterPrice,
    regisNoButton,
    showPdfRegistion,
    ...mapMutations(['changeLayoutHandle']),
    addProduct () {
      this.dialogVisibel = true
      this.getProductList()
    },
    // 判断供应商是否入住M平台
    isSettleInM () {
      this.$axios({
        method: 'get',
        url: enterMplatform,
        params: {
          supplierId: this.pushSupplier.supplierId
        }
      }).then(res => {
        this.pushSupplier.isCheckInMplatform = res.data.payload
      })
    },
    // 获取供应商
    getPartnerList () {
      // 合作类型 provider供应商、customer客户 多种逗号分隔
      this.$axios({
        method: 'get',
        url: partnerList,
        params: {
          partnership: 'provider'
        }
      }).then(res => {
        this.partnerListData = res.data.payload || []
      })
    },
    initNavButtons () {
      const btn = {
        type: 'btn',
        arr: [
          {
            type: 'button',
            noReturn: true,
            val: '返回',
            handle: this.back
          },
          {
            type: 'danger',
            noReturn: true,
            val: '拒绝响应',
            handle: this.goRefuse
          },
          {
            type: 'primary',
            noReturn: true,
            val: '线下完成',
            handle: this.goOrderFinish
          },
          {
            type: 'primary',
            noReturn: true,
            val: '响应',
            handle: this.goResponse
          },
          {
            type: 'primary',
            noReturn: true,
            val: '推送国科',
            handle: this.back,
            disabled: true
          }
        ]
      }
      this.changeLayoutHandle(btn)
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getDetailList()
    },
    // 获取配送商对应的供应商
    changeupCompany () {
      this.$axios({
        method: 'post',
        url: enumSelectorhosDealerSuperDealer,
        data: {
          enterpriseId: this.$store.state.companyId
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        let content = obj.content
        this.changeCompanyList = content
      })
    },
    back () {
      this.$router.go(-1)
    },
    // 产品列表
    getDetailList () {
      // 手动添加的产品明细
      this.$axios({
        method: 'post',
        url: YyPssFollowOrderItemPageList,
        data: {
          pssFollowId: this.$route.query.id,
          page: this.curPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        if (obj.content) {
          obj.content.forEach(item => {
            item.isEdit = true
            item.isEditNum = true
          })
        }
        this.ordertableData = obj.content
        this.totalElements = obj.totalElements
        this.computedCountList.saleOrderAllSum = this.ordertableData ? this.ordertableData[0].prodCount : 0
        this.computedCountList.varietiesCount = this.ordertableData ? this.ordertableData[0].prodTypeCount : 0
        this.computedCountList.detailAmount = this.ordertableData ? this.ordertableData[0].orderTotalAmount : 0
      })
    },
    // 获取基本信息
    getDeverInfo () {
      this.$axios({
        method: 'get',
        url: YyPssFollowOrdergetById,
        params: {
          pssFollowId: this.$route.query.id
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.pushSupplier.supplierId = obj.upCompanyId || ''

        for (let key in obj) {
          obj[key] = obj[key] || ``
          if (key === 'fileUrl') {
            obj[key] = obj[key] || []
          }
          if (!obj[key]) {
            obj[key] = `--`
          }
          if (key === 'orderStatus') {
            obj[key] = ORDER_STATUS[obj[key]]
          }
          if (key === 'sickSex') {
            obj[key] = sexMap[obj[key]]
          }
        }
        this.topInfo = obj
        // 上边同步推送供应商，供应商默认选中新建订单中选择的供应商

        const { fileUrl } = this.topInfo
        this.topInfo.fileUrl = fileUrl || []
        this.topInfo.fileUrl.forEach(item => {
          item.type = item.fileUrl.split('').reverse().join('').split('.')[0].split('').reverse().join('').toLowerCase()
        })
        if (Number(this.$route.query.isShowList) === 0) {
          // this.computedCountList.saleOrderAllSum = this.topInfo.prodCount
          // this.computedCountList.varietiesCount = this.topInfo.prodTypeCount
          // this.computedCountList.detailAmount = this.topInfo.orderTotalAmount
        }
      })
    },
    // remoteMethod (value, key) {
    //   this.getAuthItemName(value)
    // },
    // getAuthItemName (value) {
    //   const postData = {
    //     upEnterpriseName: value
    //   }
    //   const item = this.computedProductListSearchForm.find(item => item.key === 'upEnterpriseId')
    //   this.$axios.$post(enumSelectorhosDealerUpEnterpriseSelector, postData)
    //     .then(res => {
    //       const nameList = res.payload.content
    //       const options = nameList.map(item => {
    //         return {
    //           label: item.value,
    //           value: item.id
    //         }
    //       })
    //       this.$set(item, 'options', options)
    //     })
    //     .catch(e => {})
    //     .finally(() => {
    //     })
    // },
    searchForm (condition) {
      this.dialogPageList.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    resetForm (condition) {
      this.dialogPageList.curPage = 1
      this.searchQuery = condition
      this.getProductList()
    },
    // 添加产品table
    getProductList () {
      const postData = {
        // ...this.extraQuery,
        ...this.searchQuery,
        page: this.dialogPageList.curPage,
        pageSize: this.pageSize,
        // hospitalId: this.topInfo.hospitalId,
        // downEnterpriseId: this.topInfo.upCompanyId
        merchantCompanyId: this.topInfo.hospitalId,
        enterpriseId: this.$store.state.companyId, // 当前公司id
        upEnterpriseId: this.pushSupplier.supplierId,
        priceModelType: 0
      }
      const url = enumSelectorhosDealerUpEnterpriseSelector
      this.$axios({
        method: 'post',
        url: getAuthItemCommonQuery,
        data: postData
      }).then(res => {
        // eslint-disable-next-line no-undef
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.dialogTableData = obj.content
        this.dialogPageList.totalElements = obj.totalElements
      })
    },
    goResponse () {
      if (!this.pushSupplier.isPushSupplier) {
        this.responseData('noPush')
      } else {
        if (!this.pushSupplier.supplierId) {
          this.$message({
            type: 'warning',
            message: '请选择同步推送的供应商！'
          })
        } else if (!this.pushSupplier.isCheckInMplatform) {
          this.$message({
            type: 'warning',
            message: '供应商必须入住M平台！'
          })
        } else {
          this.responseData('yesPush')
        }
      }
    },
    // 处理一下响应的数据
    responseData (type) {
      let arr = this.tableData.map(item => {
        return {
          itemCode: item.code,
          nameCn: item.prodName,
          specification: item.spec,
          productType: item.model,
          unit: item.unit,
          price: item.buyPrice || 0,
          registrationNumber: item.registNo,
          category: item.bigType,
          supplierName: item.upEnterpriseName,
          hspProdCode: item.hosProdCode,
          hosProdCode: item.hosProdCode,
          itemId: item.hosAuthItemId,
          authProdId: item.dealerAuthItemId,
          manufacturer: item.manufacturer,
          minUnit: item.unit,
          purchaseNum: item.purchaseNum,
          registrationId: item.registId
        }
      })
      let dataForm = {
        pssFollowId: this.$route.query.id,
        // supplierId: this.pushSupplier.supplierId,
        // supplierName: '',
        checkAgent: this.pushSupplier.isPushSupplier ? 1 : 0
      }
      if (type === 'yesPush') {
        // 如果推送供应商，就加上供应商id和名称字段
        // 根据供应商id查找供应商名称
        this.partnerListData.forEach(item => {
          if (item.companyId === this.pushSupplier.supplierId) {
            dataForm.supplierName = item.companyName
          }
        })
        dataForm.supplierId = this.pushSupplier.supplierId
      }
      this.$axios({
        method: 'post',
        url: YyPssFollowOrderResponseOrder,
        data: dataForm
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '响应成功' })
            this.$router.go(-1)
          } else {
            this.$message({
              type: 'warning',
              message: '响应失败'
            })
          }
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '响应失败'
          })
        })
    },
    handleSelectionChange (arr) {
      this.tableSelectData = arr
    },
    removeProducts (data) {
      this.$confirm('此操作将删除产品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = []
        if (data && data !== undefined) {
          params.push(data.pssFollowDetailId)
        } else {
          if (!this.tableSelectData.length) {
            this.$message({ type: 'warning', message: '请选择需要删除的产品' })
            return
          }
          this.tableSelectData.forEach((item) => {
            params.push(item.pssFollowDetailId)
          })
        }
        this.$axios({
          method: 'post',
          url: YyPssFollowOrderDelProduct,
          data: { ids: params }
        })
          .then(res => {
            let code = hasIn(res, 'data.code') ? res.data.code : ''
            if (Number(code) === 0) {
              this.$message({ type: 'success', message: '删除成功' })
            } else {
              this.$message({
                type: 'warning',
                message: '删除失败'
              })
            }
            this.getDetailList()
          })
          .catch(res => {
            this.$message({
              type: 'warning',
              message: '删除失败'
            })
          })
      })
    },
    dialogHandleSelectionChange (arr) {
      this.dialogTableSelectData = arr
    },
    // 拒绝响应
    goRefuse () {
      this.$axios({
        method: 'get',
        url: YyPssFollowOrderRefuse,
        params: {
          pssFollowId: this.$route.query.id
        }
      }).then(res => {
        let code = hasIn(res, 'data.code') ? res.data.code : ''
        if (code === '0') {
          this.$message({ type: 'success', message: '拒绝成功' })
          this.$router.go(-1)
        }
      })
    },
    // 线下完成
    goOrderFinish () {
      this.$axios({
        method: 'get',
        url: YyPssFollowOrderFinish,
        params: {
          pssFollowId: this.$route.query.id
        }
      }).then(res => {
        let code = hasIn(res, 'data.code') ? res.data.code : ''
        if (code === '0') {
          this.$message({ type: 'success', message: '提交成功' })
          this.$router.go(-1)
        }
      })
    },
    confirmDialog () {
      let maps = {}
      this.dialogTableSelectData.forEach(item => {
        let key = item.id
        let value = item.hosAuthItemId
        maps[key] = value
      })
      let params = {
        companyId: this.topInfo.hospitalId,
        pssFollowId: this.topInfo.pssFollowId,
        maps: maps
      }
      this.$axios({
        method: 'post',
        url: YyPssFollowOrderAddOrder,
        data: params
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '添加成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '添加失败'
            })
          }
          this.getDetailList()
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '添加失败'
          })
        })
    },
    handleCurrentChange (page) {
      this.curPage = page
      this.getDetailList()
    },
    cancelDialog () {
      this.dialogVisibel = false
    },
    closeDialog () {
      this.dialogVisibel = false
    },
    dialogHandleSizeChange (size) {
      this.dialogPageList.pageSize = size
      this.getProductList()
    },
    dialogHandleCurrentChange (curPage) {
      this.dialogPageList.curPage = curPage
      this.getProductList()
    },
    changePriceSbumit (data, value) {
      data.row.isEdit = true
      this.$axios({
        method: 'post',
        url: YyPssFollowOrderUpdatePrice,
        data: {
          pssFollowDetailId: data.row.pssFollowDetailId,
          price: data.row.price
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '编辑成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '编辑失败'
            })
          }
          this.getDetailList()
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '编辑失败'
          })
        })
    },
    changeNumSbumit (data, value) {
      data.row.isEdit = true
      this.$axios({
        method: 'post',
        url: YyPssFollowOrderUpdateNumber,
        data: {
          pssFollowDetailId: data.row.pssFollowDetailId,
          purchaseNum: data.row.purchaseNum
        }
      })
        .then(res => {
          let code = hasIn(res, 'data.code') ? res.data.code : ''
          if (Number(code) === 0) {
            this.$message({ type: 'success', message: '编辑成功' })
          } else {
            this.$message({
              type: 'warning',
              message: '编辑失败'
            })
          }
          this.getDetailList()
        })
        .catch(res => {
          this.$message({
            type: 'warning',
            message: '编辑失败'
          })
        })
    }
  }
}
</script>
<style lang="less">
.response-box {
  // height: 100%;
  // overflow: auto;
  .response-box-cont {
    // height: 100%;
    // overflow: auto;
    .header-form {
      .header-form-item {
        margin-right: 50px;
      }
    }
    .push-supplier-box {
      height: 55px;
      display: flex;
      align-items: center;
      p {
        margin-left: 30px;
      }
    }
  }
  .pagination {
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 0;
  }
  .title {
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }
}
</style>
